# Copyright (c) 2009, Michal Mazurek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 
#    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#    * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


import SocketServer, cPickle, mmap, sys, traceback, logging

from SocketServer import BaseRequestHandler

from __init__ import RequestedObjectDoesNotExists, NoObjectRequested



if __name__ == "__main__":
    logger = logging.getLogger("PyPickleRPCServer")
    logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler("rpcserver.log")
    
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)

class FinishedConnection (Exception): pass

class RPCRequestHandler(BaseRequestHandler):
    
    headers = {}
    headers_to_send = {}
    objects = {}
    connected = True
    def __init__(self, request, client_address, server):
    
        logger.info("Connection from '%s'" % str(client_address))
        BaseRequestHandler.__init__(self, request, client_address, server)
        
        self.objects = server.objects
        
    def get_headers(self):
        char = ""
        headstring = ""
        while True:
            lastchar = char
            char = self.request.recv(1)
            if len(char) == 0:
                if self.connected:
                    self.finish()
                break
            
            if char == "\n" and lastchar == "\n":
                break
            
            headstring += char
            
        headers = {}
        for line in headstring.splitlines():
            key, val = line.split(":")
            headers[key] = val
            pass
        
        if "--debug" in sys.argv:
            logger.debug("Received Headers\n%s" % headstring.rstrip())
        
        self.headers = headers
        
    
    def get_requested_object(self):
        
        self.get_headers()
        if not self.connected:
            #self.finish()
            raise FinishedConnection, ''
        if self.headers.has_key("Requested-Object"):
            if self.server.objects.has_key(self.headers["Requested-Object"].strip()):
                return self.server.objects[self.headers["Requested-Object"].strip()]
            else:
                raise RequestedObjectDoesNotExists, self.headers["Requested-Object"]
        else:
            raise NoObjectRequested, "Please request an object first"
        
    def send_exception(self):
        
        headers = "Traceback:true\n"
        exc_info = sys.exc_info()
        body = exc_info[0], exc_info[1], traceback.extract_tb(exc_info[2])
        
        pickles = cPickle.dumps(body)
            
        contentlength = len(pickles)
        lenstr = "Content-Length:%d\n\n" % contentlength
        self.request.send(headers+lenstr+pickles)
            
        pass
        
    def send_response(self, headers, message):
        
        body = ""
        
        pickles = cPickle.dumps(message)
        headers['Content-Length'] = str(len(pickles))
        
        for name in headers.keys():
            body += "%s:%s\n" % (name, headers[name])
        
        body += "\n" #headers delimeter from body
        body += pickles
        
        send =  self.request.send(body)
        if "--debug" in sys.argv:
            logger.debug("I have sent %d of data.\n%s" % (send, body))
        return send
        
    def handle(self):
        
        
        dobreak = False
        try:
            served_object = self.get_requested_object()
            logger.info("Instanciated Object %s" % served_object.__name__)
            pickles = cPickle.dumps("ok")
            self.request.send("Requested-Object:%s\nContent-Length:%d\n\n%s" % (served_object.__name__, len(pickles), pickles))
            served_object_instance = served_object()
            
        except RequestedObjectDoesNotExists:
            self.send_exception()
            if self.connected:
                self.finish()
            return ""
        except FinishedConnection:
            #self.finish()
            return ""
        
        while self.connected:
            
            picklestr = ""
            headers = ""
            self.get_headers()
            #check if after getting headers, connection was lost
            if not self.connected:
                break
            
            if self.headers.has_key("Finish-Connection"):
                if self.headers["Finish-Connection"].strip().lower() == "true":
                    break
            contentlength = int(self.headers["Content-Length"])
            packetsize = 1024
            downloaded = 0
            while True:
                
                if downloaded == int(contentlength):
                    break
                
                if downloaded+packetsize > int(contentlength):
                    packetsize = int(contentlength)-downloaded
                buf = self.request.recv(packetsize)
                
                # connection lost?
                if len(buf) == 0:
                    if self.connected:
                        self.finish()
                    break
                
                downloaded += packetsize
                picklestr = picklestr+buf
                
            request = cPickle.loads(picklestr)
            
            try:
                result = served_object_instance.__getattribute__(request[0])
                body = result.__call__(*request[1], **request[2])
                
            except:
                headers += "Traceback:true\n"
                exc_info = sys.exc_info()
                body = exc_info[0], exc_info[1], traceback.extract_tb(exc_info[2])
                #dobreak = True
            pickles = cPickle.dumps(body)
            
            contentlength = len(pickles)
            lenstr = "Content-Length:%d\n\n" % contentlength
            self.request.send(headers+lenstr+pickles)
            
            if dobreak:
                break
        del served_object_instance
            
    def finish(self):
        self.connected = False
        logger.info("Closing session with '%s'" % str(self.client_address))
        self.request.close()


class RPCServerMixIn(object):
    
    objects = {}
    
    def add_object(self, object):
        self.objects[object.__name__] = object
        logger.debug("Loaded object '%s'", object.__name__)        

    def handle_error(self, request, client_address, e = ""):
        
        logger.exception("%s from %s, closing connection..." % (str(e), str(client_address)))
        #request.close()
        
    pass


class UnixSocketRPCServer(RPCServerMixIn, SocketServer.ThreadingUnixStreamServer):

    def __init__(self, server_address, RequestHandler = RPCRequestHandler):
        
        SocketServer.ThreadingUnixStreamServer.__init__(self, server_address, RequestHandler)
    
try:
    import M2Crypto
    from M2Crypto import SSL
        
    class SSLRPCServer(RPCServerMixIn, SSL.SSLServer):
        objects = {}
        
        def __init__(self, server_address, cert, certkey, ca):
            global cafile
            cafile = ca
            RequestHandler = RPCRequestHandler
            logger.info("Starting PickleRPCServer...")
            def verify_cb(ok, store) :
                global cafile
                cert = store.get_current_cert()
                mecert = M2Crypto.X509.load_cert(cafile)
                if mecert.get_fingerprint(md="sha1") == cert.get_fingerprint(md="sha1"):
                    return 1
                else:
                    return ok
            
            # setup an SSL context.
            context = SSL.Context("sslv23")
            #
            #context.load_verify_locations("./ca.crt")
            context.load_client_ca(ca)       
            if context.load_verify_locations(ca, "./") != 1:
                raise Exception('CA certificates not loaded')
            context.load_client_ca(ca)        
            context.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 1, verify_cb)
            #context.set_verify(SSL.verify_none, 1,verify_cb )
            # load up certificate stuff.
            if "--debug" in sys.argv:
                logger.debug("Using certificate %s", cert)
            context.set_allow_unknown_ca(1)
            if "--debug" in sys.argv:
                context.set_info_callback()
            context.load_cert(cert, certkey)
            #context.use_certificate_file(CERT_FILE)
            SSL.ThreadingSSLServer.__init__(self, server_address, RequestHandler, context)
            
            
        
        def serve_forever(self):
            logger.info("Serving PickleRPC on %s", self.server_address)
            SSL.ThreadingSSLServer.serve_forever(self)
        
        
 
    class SSLThreadedRPCServer(SocketServer.ThreadingMixIn, SSLRPCServer):
        pass       
    
    
    
except ImportError:
    
    class SSLRPCServer(object):
        """
            Module M2Crypto is not installed.
        """
        def __init__(self, *args, **kw):
            
            print "Module M2Crypto is not installed."
            sys.exit(1)
            
            pass

RPCServer = SSLRPCServer